/**
 * DOM 操作相关工具函数
 */

/**
 * 获取当前对话 ID
 * @returns 当前对话 ID，如果未找到则返回 null
 */
export function getCurrentChatId(): string | null {
  // 从 URL 路径中获取
  
  // 从 DOM 元素中获取
  const messageContainer = document.querySelector('div[data-id]');
  if (messageContainer) {
    const dataId = messageContainer.getAttribute('data-id');
    if (dataId) {
      const parts = dataId.split('_');
      if (parts.length > 1) {
        return parts[1]; // 返回类似 "85293364278@c.us" 的ID
      }
    }
  }
  
  return null;
}

/**
 * 获取聊天标题
 * @returns 聊天标题，如果未找到则返回 null
 */
export function getCurrentChatNickname(): string | null {
  const titleElement = document.querySelector('#main span[dir="auto"]');
  if (titleElement) {
    return titleElement.textContent?.trim() || null;
  }
  return null;
}

/**
 * 设置编辑器内容的增强版本
 * @param text 要设置的文本内容
 * @returns 是否成功设置内容
 */
export async function setEditorContent2(text: string): Promise<boolean> {
    try {
        // 找到编辑器元素
        const editor = document.querySelector('#main div[data-lexical-editor="true"]') as HTMLDivElement;
        if (!editor) {
            throw new Error('Editor not found');
        }

        // 聚焦编辑器
        editor.focus();

        // 清除现有内容
        const range = document.createRange();
        range.selectNodeContents(editor);
        const selection = window.getSelection();
        if (!selection) {
            throw new Error('Selection API not supported');
        }
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('delete', false);

        // 等待一下以确保内容被清除
        await new Promise(resolve => setTimeout(resolve, 50));

        // 插入新内容
        document.execCommand('insertText', false, text);

        // 触发输入事件
        const inputEvent = new Event('input', { bubbles: true });
        editor.dispatchEvent(inputEvent);

        // 触发 compositionend 事件以确保 WhatsApp 识别到更改
        const compositionEvent = new Event('compositionend', {
            bubbles: true,
            cancelable: true,
        });
        editor.dispatchEvent(compositionEvent);

        return true;
    } catch (error) {
        console.error('Error updating editor:', error);
        // 如果上面的方法失败，尝试直接设置 textContent
        try {
            const editor = document.querySelector('#main div[data-lexical-editor="true"]') as HTMLDivElement;
            if (editor) {
                editor.textContent = text;
                editor.dispatchEvent(new Event('input', { bubbles: true }));
                editor.dispatchEvent(new Event('compositionend', { bubbles: true }));
                return true;
            }
            return false;
        } catch (fallbackError) {
            console.error('Fallback method also failed:', fallbackError);
            return false;
        }
    }
}

/**
 * 在WhatsApp侧边栏搜索框中输入客户名称
 * @param customerName 要输入的客户名称
 * @returns 是否成功设置内容
 */
export async function setWhatsAppSearchInput(customerName: string): Promise<boolean> {
    try {
      // 点击清空按钮 #side span[data-icon="x-alt"]的parent
        const clearButton = document.querySelector('#side span[data-icon="x-alt"]');
        if (clearButton) {
            console.log('点击清空按钮');
            (clearButton as HTMLElement).click();
        } else {
            console.log('未找到清空按钮');
        }
        // 等待2秒钟
        await new Promise(resolve => setTimeout(resolve, 500));
        // 找到侧边栏搜索输入框
        const searchInput = document.querySelector('#side div[data-lexical-editor="true"]') as HTMLDivElement;
        if (!searchInput) {
            console.error('WhatsApp搜索输入框未找到');
            return false;
        }

        // 聚焦输入框
        searchInput.focus();
      
        // 清除现有内容
        const range = document.createRange();
        range.selectNodeContents(searchInput);
        const selection = window.getSelection();
        if (!selection) {
            throw new Error('Selection API not supported');
        }
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('delete', false);
        
        // 等待一下以确保内容被清除
        await new Promise(resolve => setTimeout(resolve, 50));
        
        // 插入客户名称
        document.execCommand('insertText', false, customerName);
        
        // 触发输入事件
        const inputEvent = new Event('input', { bubbles: true });
        searchInput.dispatchEvent(inputEvent);
        
        // 触发 compositionend 事件以确保 WhatsApp 识别到更改
        const compositionEvent = new Event('compositionend', {
            bubbles: true,
            cancelable: true,
        });
        searchInput.dispatchEvent(compositionEvent);
        
        console.log(`已在WhatsApp搜索框中输入: ${customerName}`);
        return true;
    } catch (error) {
        console.error('设置WhatsApp搜索输入框内容时出错:', error);
        
        // 如果上面的方法失败，尝试直接设置 textContent
        try {
            const searchInput = document.querySelector('#side div[data-lexical-editor="true"]') as HTMLDivElement;
            if (searchInput) {
                searchInput.textContent = customerName;
                searchInput.dispatchEvent(new Event('input', { bubbles: true }));
                searchInput.dispatchEvent(new Event('compositionend', { bubbles: true }));
                return true;
            }
            return false;
        } catch (fallbackError) {
            console.error('备用方法也失败了:', fallbackError);
            return false;
        }
    }
}

/**
 * 模拟真实用户点击的高级函数
 * @param element 要点击的元素
 * @returns 是否成功执行点击操作
 */
export async function simulateRealUserClick(element: HTMLElement): Promise<boolean> {
    try {
        if (!element) return false;
        
        const rect = element.getBoundingClientRect();
        const centerX = Math.floor(rect.left + rect.width / 2);
        const centerY = Math.floor(rect.top + rect.height / 2);
        
        // console.log(`在坐标(${centerX}, ${centerY})模拟真实用户点击`);
        
        // 1. 尝试使用 PointerEvent (更现代的事件类型)
        const pointerEvents = [
            new PointerEvent('pointerover', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY
            }),
            new PointerEvent('pointerdown', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY,
                button: 0,
                buttons: 1
            }),
            new PointerEvent('pointerup', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY,
                button: 0,
                buttons: 0
            })
        ];
        
        for (const event of pointerEvents) {
            element.dispatchEvent(event);
            await new Promise(resolve => setTimeout(resolve, 10));
        }
        
        // 2. 尝试使用 TouchEvent (移动设备事件)
        const touchStart = new TouchEvent('touchstart', {
            bubbles: true,
            cancelable: true,
            view: window,
            touches: [new Touch({
                identifier: Date.now(),
                target: element,
                clientX: centerX,
                clientY: centerY,
                pageX: centerX,
                pageY: centerY
            })]
        });
        
        const touchEnd = new TouchEvent('touchend', {
            bubbles: true,
            cancelable: true,
            view: window,
            touches: []
        });
        
        element.dispatchEvent(touchStart);
        await new Promise(resolve => setTimeout(resolve, 50));
        element.dispatchEvent(touchEnd);
        
        // 3. 尝试使用 MouseEvent 完整序列
        const mouseEvents = [
            new MouseEvent('mouseover', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY
            }),
            new MouseEvent('mouseenter', {
                bubbles: false, // mouseenter 不冒泡
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY
            }),
            new MouseEvent('mousemove', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY
            }),
            new MouseEvent('mousedown', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY,
                button: 0,
                buttons: 1
            }),
            new MouseEvent('mouseup', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY,
                button: 0,
                buttons: 0
            }),
            new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window,
                clientX: centerX,
                clientY: centerY,
                button: 0,
                buttons: 0
            })
        ];
        
        for (const event of mouseEvents) {
            element.dispatchEvent(event);
            await new Promise(resolve => setTimeout(resolve, 10));
        }
        
        // 4. 尝试直接调用元素的 onclick 属性
        if (typeof element.onclick === 'function') {
            element.onclick(new MouseEvent('click'));
        }
        
        // 5. 尝试使用 HTMLElement 的 click 方法
        element.click();
        
        return true;
    } catch (error) {
        // console.error('模拟真实用户点击失败:', error);
        return false;
    }
}

/**
 * 点击WhatsApp搜索结果中的第一个对话
 * @returns 是否成功点击
 */
export async function clickFirstSearchResult(): Promise<boolean> {
    try {
        
        // 修改等待逻辑，最长等待5秒，循环检查目标元素是否出现
        let listItems: NodeListOf<Element> = document.querySelectorAll('#side div[role="listitem"]');
        let attempts = 0;
        const maxAttempts = 50; // 5秒 = 50次 * 100毫秒
        
        while (listItems.length <= 1 && attempts < maxAttempts) {
            await new Promise(resolve => setTimeout(resolve, 100)); // 每100毫秒检查一次
            listItems = document.querySelectorAll('#side div[role="listitem"]');
            attempts++;
        }
        
        if (listItems.length > 1) {
            // 获取第二个搜索结果（第一个通常是标题）
            const targetResult = listItems[1] as HTMLElement;
            
            // 尝试找到实际可点击的元素
            const clickableElement = targetResult.querySelector('div._ak72') || 
                                    targetResult.querySelector('div._ak73') || 
                                    targetResult.querySelector('div[tabindex="-1"]') || 
                                    targetResult;
            
            // 使用新的模拟真实用户点击方法
            await simulateRealUserClick(clickableElement as HTMLElement);
            
            // 如果上面的方法失败，尝试点击内部元素
            const innerElements = [
                targetResult.querySelector('div._ak8n'), // 头像容器
                targetResult.querySelector('div._ak8l'), // 信息容器
                targetResult.querySelector('div._ak8q'), // 名称容器
                targetResult.querySelector('div._ak8o'), // 消息容器
                targetResult.querySelector('img._ao3e'), // 头像图片
                targetResult.querySelector('span.matched-text') // 匹配的文本
            ].filter(el => el !== null) as HTMLElement[];

            
            for (const element of innerElements) {
                await simulateRealUserClick(element);
                await new Promise(resolve => setTimeout(resolve, 100));
            }
            
            // 尝试直接操作DOM元素
            try {
                const items = document.querySelectorAll('#pane-side div.x10l6tqk.xh8yej3.x1g42fcv[role="listitem"]');
                if (items.length > 1) {
                    const target = items[1];
                    
                    // 尝试点击各种可能的元素
                    const clickables = [
                        target.querySelector('div[tabindex="-1"]'),
                        target.querySelector('div._ak8n'), // 头像容器
                        target.querySelector('div._ak8l'), // 信息容器
                        target.querySelector('img._ao3e'), // 头像图片
                        target
                    ].filter(el => el !== null) as HTMLElement[];
                    
                    for (const el of clickables) {
                        await simulateRealUserClick(el);
                        await new Promise(resolve => setTimeout(resolve, 100));
                    }
                }
            } catch (directError) {
                console.warn('直接DOM操作失败:', directError);
            }
            
            // 尝试使用React事件处理
            try {
                // 获取可能存储React实例的属性
                const reactProps = Object.getOwnPropertyNames(targetResult).find(
                    prop => prop.startsWith('__reactProps$') || prop.startsWith('__reactEventHandlers$')
                );
                
                if (reactProps) {
                    const handlers = (targetResult as any)[reactProps];
                    
                    // 尝试调用onClick或onMouseDown等处理函数
                    if (handlers.onClick) {
                        handlers.onClick({
                            preventDefault: () => {},
                            stopPropagation: () => {},
                            nativeEvent: new MouseEvent('click')
                        });
                    } else if (handlers.onMouseDown) {
                        handlers.onMouseDown({
                            preventDefault: () => {},
                            stopPropagation: () => {},
                            nativeEvent: new MouseEvent('mousedown')
                        });
                    }
                }
            } catch (reactError) {
                console.warn('React事件处理尝试失败:', reactError);
            }

            // 等待一段时间，检查是否成功打开对话
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            // 检查是否成功打开对话（通过检查主区域是否显示）
            const mainArea = document.querySelector('#main');
            return mainArea !== null;
        }
        
        console.warn('未找到搜索结果');
        return false;
    } catch (error) {
        console.error('点击搜索结果时出错:', error);
        return false;
    }
}

/**
 * 搜索并打开WhatsApp对话
 * 结合搜索输入和点击第一个结果的功能
 * @param customerName 要搜索的客户名称
 * @returns 是否成功打开对话
 */
export async function searchAndOpenChat(customerName: string): Promise<boolean> {
    try {
        // 先在搜索框中输入客户名称
        const searchSuccess = await setWhatsAppSearchInput(customerName);
        if (!searchSuccess) {
            return false;
        }
        // 减少等待时间，因为clickFirstSearchResult已经有智能等待逻辑
        await new Promise(resolve => setTimeout(resolve, 300));
        // 然后点击第一个搜索结果
        const clickSuccess = await clickFirstSearchResult();
        return clickSuccess;
    } catch (error) {
        console.error('搜索并打开对话时出错:', error);
        return false;
    }
}


/**
 * 监听role="listitem"的点击事件，仅限于aria-label="对话列表"下的元素
 * @param callback 点击事件的回调函数
 * @returns 移除事件监听器的函数
 */
export function listenToListItemClicks(callback: (event: MouseEvent, element: HTMLElement) => void): () => void {
    // 使用事件委托来监听所有可能的listitem点击
    const clickHandler = (event: MouseEvent) => {
        // 从事件目标开始向上查找role="listitem"的元素
        let target = event.target as HTMLElement;
        let listItem: HTMLElement | null = null;
        
        // 向上遍历DOM树查找role="listitem"的元素
        while (target && target !== document.body) {
            if (target.getAttribute('role') === 'listitem') {
                listItem = target;
                  const fiberKey = Object.keys(target).find(key => key.startsWith('__reactFiber$'));
                  if (fiberKey) {
                    const fiber = (target as any)[fiberKey];
                    console.log('React Fiber:', fiber);
                  }
                break;
            }
            
            // 如果当前元素不是listitem，继续向上查找父元素
            const parent = target.parentElement;
            if (!parent) break;
            target = parent;
        }
        
        // 如果找到了listitem元素，检查它是否在aria-label="对话列表"的div下
        if (listItem) {
            let current: HTMLElement | null = listItem;
            let isInChatList = false;
            
            // 向上查找是否有aria-label="对话列表"的祖先元素
            while (current && current !== document.body) {
                if (current.getAttribute('aria-label') === '对话列表') {
                    isInChatList = true;
                    break;
                }
                current = current.parentElement;
            }
            
            // 只有当元素在对话列表中时才调用回调
            if (isInChatList) {
                callback(event, listItem);
            }
        }
    };
    
    // 添加事件监听器到document
    document.addEventListener('click', clickHandler, true);
    
    // 返回一个函数，用于移除事件监听器
    return () => {
        document.removeEventListener('click', clickHandler, true);
    };
}
